'use strict';

const Controller = require('egg').Controller;

class Address1Controller extends Controller {
    //创建 添加
    async create() {
        //ctx  app  service config  logger
        let {ctx,service} = this;
        //接收前端传递的参数
        let {username,phone,area,detail,num} = ctx.request.body;
        //容错处理
        if(username && /^\d{11}$/.test(phone) && area && detail && num){
            //添加
            try{
                //和数据交互，向数据库添加一条数据
                await service.address.add(username,phone,area,detail,num);
                ctx.body = {
                    code:1,
                    msg:'添加成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //删除
    async destroy(){
        let {ctx,service} = this;
        let {id} = ctx.params;
        //容错处理
        if(id){
            try{
                await service.address.del(id);
                ctx.body = {
                    code:1,
                    msg:'删除成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }    
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //更新
    async update(){
        //ctx  app  service config  logger
        let {ctx,service} = this;
        //接收前端传递的参数
        let {username,phone,area,detail,num} = ctx.request.body;
        let {id} = ctx.params;
        //容错处理
        if(username && /^\d{11}$/.test(phone) && area && detail && num && id){
            //添加
            try{
                //和数据交互，向数据库更新一条数据
                await service.address.edit(username,phone,area,detail,num,id);
                ctx.body = {
                    code:1,
                    msg:'修改成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //查询
    async index(){
        let {ctx,service} = this;
        let list = await service.address.list();
        ctx.body = {
            code:1,
            data:list
        }
    }
}

module.exports = Address1Controller;
